package logic

import (
	"context"
	"encoding/json"
	"time"
	"zhihu-new/models/cache"
	"zhihu-new/models/mysql"

	"zhihu-new/zhihurpc/internal/svc"
	"zhihu-new/zhihurpc/zhihurpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type HeatProblemLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewHeatProblemLogic(ctx context.Context, svcCtx *svc.ServiceContext) *HeatProblemLogic {
	return &HeatProblemLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *HeatProblemLogic) HeatProblem(in *zhihurpc.HeatProblemRequest) (*zhihurpc.HeatProblemResponse, error) {
	// todo: add your logic here and delete this line

	var problem []mysql.Problem
	query := mysql.DB.Debug().Limit(10).Order("heat desc")
	get := cache.Rdb.Get(l.ctx, "problemHeat10")
	if get.Val() == "" {

		query.Find(&problem)

		marshal, _ := json.Marshal(problem)
		cache.Rdb.Set(l.ctx, "problemHeat10", marshal, time.Hour*24)
	} else {

		json.Unmarshal([]byte(get.Val()), &problem)

	}

	var problemList []*zhihurpc.HeatProblem

	for _, m := range problem {
		list := zhihurpc.HeatProblem{
			Id:      int64(m.ID),
			Title:   m.Title,
			Context: m.Context,
			Name:    m.User.Nickname,
			Heat:    int64(m.Heat),
		}
		problemList = append(problemList, &list)
	}
	return &zhihurpc.HeatProblemResponse{List: problemList}, nil
}
